﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;
using System.Data.Objects;
using System.Data;
using System.Reflection;

namespace RentAWorker.DataAccess.Interfaces
{
    public static class ObjectContextExtensions
    {
        public static void UpdateObject(this ObjectContext context, EntityObject objectDetached)
        {
            if (objectDetached.EntityState == EntityState.Detached)
            {
                object currentEntityInDb = null;

                if (context.TryGetObjectByKey(objectDetached.EntityKey, out currentEntityInDb))
                {
                    context.ApplyPropertyChanges(objectDetached.EntityKey.EntitySetName, objectDetached);

                    //(CDLTLL)Apply property changes to all referenced entities in context 
                    context.ApplyReferencePropertyChanges(objectDetached, (EntityObject)currentEntityInDb);
                }
                else
                {
                    throw new ObjectNotFoundException();
                }
            }
        }


        public static void ApplyReferencePropertyChanges(this ObjectContext context, EntityObject newEntity, EntityObject originalEntity)
        {
            foreach (var relatedEnd in ((IEntityWithRelationships)originalEntity).RelationshipManager.GetAllRelatedEnds())
            {
                var oldRef = relatedEnd as EntityReference;
                if (oldRef != null)
                {
                    // this related end is a reference not a collection 
                    var newRef = ((IEntityWithRelationships)newEntity).RelationshipManager.GetRelatedEnd(oldRef.RelationshipName, oldRef.TargetRoleName) as EntityReference;
                    oldRef.EntityKey = newRef.EntityKey;
                }
            }
        }
    }
}
